package common.util;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Author: 葛成瑞
 * @Date: 2021/6/4 16:37
 */
public class YouDaoTransLate {


    //中转英
    public static String DoCnToEnTrans(String str) {
        if (StringUtils.isNotEmpty(str)) {
            if (str.contains("|")) {
                str = str.split("\\|")[1];
            }
            str = Pattern.compile ("<\\s*/?\\s*[a-zA-Z][^>]*>").matcher(str).replaceAll("");
            Map<String, Object> paramMap = new LinkedHashMap<>();
            paramMap.put("q", str);
            paramMap.put("from", "zh-CHS");
            paramMap.put("to", "en");
            String body = HttpUtil.post("http://10.1.1.17:18081/v2/translate_a", paramMap);
            JSONObject object = JSONObject.parseObject(body);
            if (object.getString("errorCode").equals("0")) {
                String translationResults = object.getJSONArray("translationResults").getJSONObject(0).getString("translation");
                return translationResults;
            } else {
                return "";
            }
        } else {
            return "";
        }

    }

    public static void main(String[] args) {
        System.out.println(DoCnToEnTrans("你好"));
    }


}
